import requests
class Agent:
    # name="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:128.0) Gecko/20100101 Firefox/128.0"
    name="myapp/5.0"
    domain="http://localhost:8000/"
    username="aaa"
    password="bbb"
    def __init__(self,name=None,domain=None):
        self.cookies = {}
        if name is None:
            self.name=Agent.name
        if domain is None:
            self.domain=Agent.domain
    def login(self):
        """
        获取cookie
        登录
        :return:
        """
        res = requests.get(self._build_url("admin/index/login"),headers=self._build_header())
        if res.status_code != requests.codes.ok:
            raise Exception("登录异常！")
        self.cookies.clear()
        for item in res.cookies.items():
            self.cookies[item[0]]=item[1]
        res = requests.post(self._build_url("admin/index/login"), data={"username":Agent.username,"password":Agent.password},headers=self._build_header(),cookies=self.cookies)
        if res.status_code != requests.codes.ok:
            raise Exception("登录异常！")
        url = self._build_url("admin/index/index")
        if url != res.url:
            raise Exception("登录失败！")
        return True


    def _build_header(self,params:dict=None):
        headers = {'user-agent': self.name}
        if params is not None:
            headers.update(params)
        return headers
    def _build_url(self,path=""):
        return f"{self.domain}{path}"